import logging, os
import re
import ConfigParser
import csv
from win32com.makegw.makegwparse import AllConverters



iniFile='script-automatic.ini'

def setIniFile(name):
    global iniFile
    iniFile=name

logger = logging.getLogger(iniFile)




def readConfig():
    config = ConfigParser.RawConfigParser()
    try:
        config.read(iniFile) 
    except Exception :
        pass
    return config

    
def configureLoger(logger, fileName='log.txt', consoleLog=True, fileLog=True, consoleLevel='DEBUG', fileLevel='DEBUG', overwrite=False):
    config = readConfig()   
    try:
        consoleLog = config.getboolean('log', 'consoleLog')
        fileLog = config.getboolean('log', 'fileLog')
        consoleLevel = config.get('log', 'consoleLevel')
        fileLevel = config.get('log', 'fileLevel')
        overwrite = config.getboolean('log', 'overwrite')
        fileName = config.get('log', 'fileName') 
    except Exception:
        print 'Can\'t set a logger'
        pass
    
    if  overwrite:
        try: 
            os.remove(fileName) 
        except OSError:
            pass     
    logger.setLevel('DEBUG')
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    if consoleLog: 
        consoleHandler = logging.StreamHandler()
        consoleHandler.setLevel(consoleLevel)
        consoleHandler.setFormatter(formatter)
        logger.addHandler(consoleHandler)
    if fileLog: 
        fileHandler = logging.FileHandler(fileName)
        fileHandler.setLevel(fileLevel)
        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)

def filterSections(searchPattern):
    config = readConfig()
    sections = config.sections()
    rePattern = re.compile(searchPattern, re.IGNORECASE)
    resultList = [sec for sec in sections if re.search(rePattern, sec)]
    return resultList

def getSectionParameters(sectionName):
    config = readConfig()
    itemdictionary = dict(config.items(sectionName))
    return itemdictionary

def parseFileIntoSQLList(filePath):
    try:
        openedFile = open(filePath)
        allLines = openedFile.readlines()
        withoutComments = [lane for lane in allLines if not lane.startswith(';')]
        allContent = ''.join(withoutComments)
        noEndOfLines = allContent.replace('\n', ' ')
        fileLines = noEndOfLines.split(';')
        logger.debug(' In %s read %d rows' % (filePath, len(fileLines)))        
    except Exception as e:
        logger.error('Problem with file %s, %s' % (filePath, e))
    return fileLines[0:-1]


def writeList2DToFile(filePath, rowList):
    try:
        fil = open(filePath, 'a')
        for row in rowList:
            fil.write('\n')
            for el in row:
                fil.write(str(el))
                fil.write('\t')
        fil.write('\n')
    except Exception as e:
        logger.error('Cant create file %s, %s' % (filePath, e))

def csvIntoDict(pathCSVFile, delimiter=','):
    try:
        csvContent = csv.reader(removeBlankLines(open(pathCSVFile)), delimiter=delimiter)
        header = csvContent.next()
        csvDict = []
        for row in csvContent:
            items = zip(header, row)
            temp = {}
            for (name, value) in items:
                temp[name] = value
            csvDict.append(temp)
    except Exception as e:
        logger.error('Cant parse CsvToDict file %s, %s' % (pathCSVFile, e))
    
    return csvDict

def getAllSections():
    config = readConfig()
    return config.sections()


class removeBlankLines(object):
    def __init__(self, file):
        self.file = file
    def __iter__(self):
        return (line for line in self.file if line.strip())
    def read(self):
        return ''.join(self)
    